<template>
  <div>
    <TopFilter
      ref="formpanel"
      :list="topFilterList"
      :cols="3"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :onColumnsChange="columns => this.columns = columns"
      :onRowSelectChange="getSelectData"
      :onSyncTableData="tableDataChange"
    >
    <template slot="controls">
      <el-button size="small" type="primary"   @click="exportHandleBtn">批量上报</el-button>      </template>
    </FilterTable>
    <BaseDialog
        :visible.sync="visible"
        :title="dialogTitle"
        destroyOnClose
        width="1050px"
        :containerStyle="{height: '100%', overflow: 'auto'}">
        <SolidReport :type="handleType" :rowData="formData" @close="closeHandler"></SolidReport>
    </BaseDialog>
  </div>
</template>
<script>
import { getUsersByPosition } from '@/api/retail/salesmanage/salesordermanage';
import { addVinOrderReport, getReportOrderDetails, qryVinOrderReport, updateSalesOrderInvoice } from '@/api/retail/salesmanage/solidReport';
import SolidReport from './solidReport'
import { dictionary } from '@/utils/dictMixin';
import { notifyAction } from '@/utils';
import moment from 'moment';
export default {
  name: 'ActualSalesReport',
  mixins: [dictionary],
  components: {
    SolidReport
  },
  data () {
    return {
      topFilterList: this.createTopFilters(),
      columns: this.createTableColumns(),
      fetchParams: {},
      fetchApi: qryVinOrderReport,
      visible: false,
      dialogTitle: '实销上报明细',
      handleType: 'show', // show add edit
      formData: {},
      theSelects: [],
      consultantList: []
    }
  },
  created () {
    this.init()
  },
  mounted () {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    init () {
      this.getEmployeeList()
    },
    async getEmployeeList() {
      let params = {
        positionCodes: [10061015],
        menuId: 223001
      }
      const res = await getUsersByPosition(params);
      // console.log('销售顾问', res)
      if (res.resultCode === 200) {
        let orginList = res.data.map(x => ({ value: x.userId, text: x.userName }));
        this.consultantList = orginList.filter((item,index,array) => {
          return array.findIndex(el=>el.value==item.value)===index
        })
        this.topFilterList.find(item => item.fieldName === 'consultant').itemList = this.consultantList;
        this.columns.find(item => item.dataIndex === 'consultant').filterItems = this.consultantList;
      }
    },
    createTopFilters () {
      return [
        {
	        type: 'INPUT',
	        label: '销售订单号',
	        fieldName: 'viNo',
	        placeholder: '请输入...',
	      },
	      {
	        type: 'INPUT',
	        label: '客户名称',
	        fieldName: 'customerName',
	        placeholder: '请输入...'
	      },
	      {
	        type: 'INPUT',
	        label: '手机号码',
	        fieldName: 'customerPhone',
	        placeholder: '请输入...'
	      },
	      {
	        type: 'SELECT',
	        label: '销售顾问',
	        fieldName: 'consultant',
          placeholder: '请选择',
          itemList: []
	      },
	      {
	        type: 'RANGE_DATE',
	        label: '上报日期',
	        fieldName: 'reportDateStart|reportDateEnd',
	        placeholder: '请选择日期...'
        },
	      {
	        type: 'INPUT',
	        label: 'VIN',
	        fieldName: 'vin',
	        placeholder: '请输入...'
	      },
	      {
	        type: 'SELECT',
	        label: '上报审核状态',
	        fieldName: 'reportStatus',
          placeholder: '请选择',
          labelWidth:'150',
          style: {'display':'block','width': 'auto','margin-left':'100px'},
          itemList: this.createDictList('2065'),
	      },
      ];
    },
    createTableColumns() {
      let _this = this
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 120,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" disabled={[20651002, 20651003, 20651004].includes(props.row.reportStatus)} onClick={() => [20651002, 20651003, 20651004].includes(props.row.reportStatus)?'':this.exportFun(props.row)}>
                  上报
                </el-button>
                <el-button size="mini" type="text" disabled={[20651002, 20651003, 20651004].includes(props.row.reportStatus)} onClick={() => [20651002, 20651003, 20651004].includes(props.row.reportStatus)?'':this.editFun(props.row)}>
                  编辑
                </el-button>
                <el-button size="mini" type="text" onClick={() => this.detailFun(props.row)}>
                  明细
                </el-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '销售订单号',
          dataIndex: 'viNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户编号',
          dataIndex: 'customerNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户名称',
          dataIndex: 'customerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '销售顾问',
          dataIndex: 'consultant',
          filterType: 'input',
          filterItems: this.consultantList,
          render: function(props){
            return <span>{_this.preCurrentText(props.row.consultant, this.filterItems)}</span>;
          }
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '手机号码',
          dataIndex: 'mobilePhone',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '上报日期',
          dataIndex: 'reportDate',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '上报审核状态',
          dataIndex: 'reportStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2065'),
          render: props => {
            return <span>{ this.preDictHandler(props.row.reportStatus, '2065') }</span>;
          }
        },
      ]
    },
    // 批量上报
    exportHandleBtn () {
      let deFineError=[['请选择一条数据','error'],['有一条信息不完整','error']]
      if (this.theSelects.length == 0){
        notifyAction(...deFineError[0])
        return
      }
      console.log(this.theSelects.length)
      let params = this.theSelects.map(item => {
        return item.soVinId
      })
      //TODO:测试
      // 验证提交
      let notOkList = this.validateParams(this.theSelects)
      if (notOkList.length === 0){
        this.exportAction(params)
      } else {
        notifyAction(...deFineError[1])
        this.editFun(notOkList[0], true)
      }
    },
    // 单个上报
    exportFun (row) {
      console.log(row)
      let params = [row.soVinId]
      // 验证提交
      let notOkList = this.validateParams([row])
      notOkList.length === 0 ? this.exportAction(params) : this.editFun(notOkList[0], true)
    },
    validateParams(row) {
      let validateList = [
        'invoiceAmount',
        'invoiceCode',
        'invoiceCustomer',
        'invoiceKind',
        'invoiceNo',
        'invoiceUrl',
        'isInsurance',
        'transactor',
        // 'invoiceMobile' 以后版本需要
      ]
      let notOkList = row.filter((itemA,index,arr) => {
        return validateList.some(itemB => itemA[itemB] == null || itemA[itemB] == undefined)
      })
      return notOkList
    },
    exportAction (params, defineMsg=[['上报成功'],['上报失败','error']]) {
      let msg = ''
      addVinOrderReport(params).then(res => {
        if (res.success) {
          msg = defineMsg[0];
          // 延迟刷新
          setTimeout(()=>{
            this.fetchParams = { ...this.fetchParams };
          },0);
        } else {
          msg = defineMsg[1];
        }
        notifyAction(...msg);
      });
    },
    editFun (row, notOk = false) {
      if (!notOk) {
        this.visible = true;
        this.handleType = 'edit';
        // 实销上报编辑
        this.dialogTitle = '实销上报编辑'
        this.formData = row;
      } else {
        this.$confirm('开票必填字段没有填写，请填写完整再上报?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.visible = true;
          this.handleType = 'edit';
          // 实销上报编辑
          this.dialogTitle = '实销上报编辑'
          this.formData = row;
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      }
    },
    detailFun (row) {
      console.log(row)
      this.visible = true;
      this.handleType = 'show';
      // 实销上报明细
      this.dialogTitle = '实销上报明细'
      this.formData = row;
    },
    tableDataChange (data, isFirst) {
      if (isFirst) {
        let disabledSelect = data.filter(row => [20651002, 20651003, 20651004].includes(row.reportStatus))
        this.$refs.table.$refs.pageTable.SET_DISABLE_SELECT(disabledSelect)
      }
    },
    changeHandle(fetchParams) {
      console.log(fetchParams)
      this.fetchParams = Object.assign({}, fetchParams);
    },
    // 被选择数据
    getSelectData (val) {
      this.theSelects = val
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    closeHandler (val) {
      console.log(val)
      this.visible = false
      if (val === 'refresh') {
        this.fetchParams = { ...this.fetchParams };
      }
    },
    // 字典数据使用前预处理
    preDictHandler(val, code){
      let resultText = val && String.prototype.includes.call(val, code) ? this.createDictText(val, code) : val;
      return resultText;
    },
    // 非字典来源数据处理
    preCurrentText(val, dataList){
      let result = (dataList && dataList.length > 0) ? dataList.find(item => item.value == val) : val
      return result ? result['text'] : val;
    },
    // 日期预处理
    preDateHandler(val, formatCode='YYYY-MM-DD HH:mm:ss') {
      let resultDate = val ? moment(Number(val)).format(formatCode) : val;
      if ((resultDate == 'Invalid date' || resultDate == 'Invalid Date') && val) {
        resultDate = moment(val).format(formatCode)
      }
      return resultDate;
    },
  }
}
</script>
<style lang="less" scoped>

</style>
